package com.ruoyi.framework.web.service;

import cn.hutool.core.lang.Validator;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.ImsYzzcSunBranch;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.tool.SmsUtil;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.system.domain.ImsVehMerUnit;
import com.ruoyi.system.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 注册校验方法
 * 
 * @author ruoyi
 */
@Slf4j
@Component
public class SysRegisterService
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private IImsYzzcSunBranchService imsYzzcSunBranchService;

    @Autowired
    private IImsVehMerUnitService iImsVehMerUnitService;

    @Autowired
    private ISysConfigService configService;

    /**
     * 注册
     */
    @Transactional(rollbackFor = Exception.class)
    public String register(RegisterBody registerBody)
    {
        String msg = "", username = registerBody.getUsername(), password = registerBody.getPassword();
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setPhonenumber(registerBody.getPhonenumber());
        sysUser.setGpsUserName(registerBody.getGpsUserName());
        sysUser.setGpsPassword(registerBody.getGpsPassWord());

        if (("true".equals(configService.selectConfigByKey("sys.account.mobileVerificationEnabled"))))
        {
            String code=redisCache.getCacheObject(registerBody.getPhonenumber());
            if (StringUtils.isEmpty(code)){
                return "验证码已过期";
            }
            if (!code.equals(registerBody.getCode().trim())){
                return "验证码验证不正确";
            }
        }

        if (StringUtils.isEmpty(username))
        {
            msg = "用户名不能为空";
        }
        else if (StringUtils.isEmpty(password))
        {
            msg = "用户密码不能为空";
        }
        else if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            msg = "账户长度必须在2到20个字符之间";
        }
        else if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            msg = "密码长度必须在5到20个字符之间";
        }
        else if (!userService.checkUserNameUnique(sysUser))
        {
            msg = "保存用户'" + username + "'失败，注册账号已存在";
        }
        else if (StringUtils.isNotEmpty(sysUser.getPhonenumber()) && !userService.checkPhoneUnique(sysUser))
        {
            msg = "保存用户'" + username + "'失败，注册手机号已存在";
        }
        else
        {
            sysUser.setNickName(username);
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            sysUser.setDelFlag(registerBody.getFlag());
            sysUser.setPhonenumber(registerBody.getPhonenumber());
            boolean regFlag = userService.registerUser(sysUser);
            if(regFlag) {
                // 获取注册用户信息
                SysUser userObj=userService.selectUserById(sysUser.getUserId());

                //注册分配角色
                if(registerBody.getRegistType()==1){
                    SysRole sysRole=new SysRole();
                    sysRole.setRoleKey("common");
                    List<SysRole> roleList= roleService.selectAllRoleList(sysRole);
                    if (ObjectUtils.isNotEmpty(roleList)){
                        Long[] arr = new Long[8];
                        Long roleId = roleList.get(0).getRoleId();
                        arr[0] = roleId;
                        userObj.setRoleIds(arr);
                        // 新增用户与角色管理
                        userService.addUserRole(userObj);
                    }
                }else{
                    ImsYzzcSunBranch imsYzzcSunBranch = new ImsYzzcSunBranch();
                    if (ObjectUtils.isNotEmpty(registerBody.getShopName())) {
                        imsYzzcSunBranch.setName(registerBody.getShopName());
                    }else{
                        imsYzzcSunBranch.setName("默认门店"+sysUser.getUserName());
                    }
                    imsYzzcSunBranch.setCreatetime(DateUtils.getNowDate());
                    imsYzzcSunBranch.setShopCheckStatus("1");
                    imsYzzcSunBranch.setUniacid(sysUser.getUserId());
                    imsYzzcSunBranch.setPic("/prod-api/profile/shop/IyiFwmMIiMMY8i8yibqWzZrqNRIQ7i.png");
                    // 新增门店
                    imsYzzcSunBranchService.insertImsYzzcSunBranch(imsYzzcSunBranch);
                    userObj.setShopIds(imsYzzcSunBranch.getId() + "");
                    // 将门店信息保存到用户信息中
                    userService.updateUser(userObj);
                    // 将特邀商户的角色赋予到用户中
                    SysRole sysRole=new SysRole();
                    sysRole.setRoleKey("special");
                    List<SysRole> roleList= roleService.selectAllRoleList(sysRole);
                    if (ObjectUtils.isNotEmpty(roleList)){
                        Long[] arr = new Long[1];
                        Long roleId = roleList.get(0).getRoleId();
                        arr[0] = roleId;
                        userObj.setRoleIds(arr);
                        // 新增用户与角色管理
                        userService.addUserRole(userObj);
                    }
                    //新增部门
                    SysDept sysDept=new SysDept();
                    sysDept.setParentId(100L);
                    sysDept.setAncestors("0,100");
                    if (ObjectUtils.isNotEmpty(registerBody.getShopName())) {
                        sysDept.setDeptName(registerBody.getShopName());
                    }else{
                        sysDept.setDeptName("默认门店"+sysUser.getUserName());
                    }
                    sysDept.setCreateBy(sysUser.getUserName());
                    sysDept.setCreateTime(DateUtils.getNowDate());
                    deptService.insertDept(sysDept);
                    //新增门店子组织架构
                    if (sysDept.getDeptId() != null) {
                        SysDept dept = new SysDept();
                        if (ObjectUtils.isNotEmpty(registerBody.getShopName())) {
                            dept.setDeptName(registerBody.getShopName());
                        }else{
                            dept.setDeptName("默认门店"+sysUser.getUserId());
                        }
                        dept.setParentId(sysDept.getDeptId());
                        dept.setStatus("0");
                        dept.setDelFlag("0");
                        deptService.insertDept(dept);
                        userObj.setDeptId(sysDept.getDeptId());
                        userService.updateUser(userObj);

                        ImsYzzcSunBranch yzzcSunBranch = new ImsYzzcSunBranch();
                        yzzcSunBranch.setId(imsYzzcSunBranch.getId());
                        yzzcSunBranch.setDeptId(dept.getDeptId());
                        imsYzzcSunBranchService.updateImsYzzcSunBranch(yzzcSunBranch);
                    }
                    // 添加公司单位信息
                    ImsVehMerUnit imsVehCusUnit = new ImsVehMerUnit();
                    imsVehCusUnit.setCustomerUnitName(registerBody.getShopName());
                    imsVehCusUnit.setPersonName(registerBody.getUsername());
                    imsVehCusUnit.setPersonTel(registerBody.getPhonenumber());
                    imsVehCusUnit.setDeptId(sysDept.getDeptId());
                    imsVehCusUnit.setCharterForm(3);
                    imsVehCusUnit.setRentalForm(1);
                    imsVehCusUnit.setCollectForm(2);
                    iImsVehMerUnitService.insertImsVehCusUnit(imsVehCusUnit);
                }
            }
            if (!regFlag)
            {
                msg = "注册失败,请联系系统管理人员";
            }
            else
            {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.REGISTER, MessageUtils.message("user.register.success")));
            }
        }
        return msg;
    }

    /**
     * 校验验证码
     * 
     * @param username 用户名
     * @param code 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid)
    {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        redisCache.deleteObject(verifyKey);
        if (captcha == null)
        {
            throw new CaptchaExpireException();
        }
        if (!code.equalsIgnoreCase(captcha))
        {
            throw new CaptchaException();
        }
    }

    public Boolean send(String phone) {
        if (Validator.isMobile(phone)) {
            String verificationCode = generateVerificationCode(6);
            String[] phonearr = {phone};
            String[] params = {verificationCode, RuoYiConfig.getSmsTime()};
            log.debug("手机号：{},验证码：{}", phone, verificationCode);
            try {
                // TODO:需要完成的功能
                //SmsSingleSenderResult sms = SmsUtil.SMS(phonearr, params, Integer.valueOf(RuoYiConfig.getSmsAppId()), RuoYiConfig.getSmsAppKey(), Integer.valueOf(RuoYiConfig.getSmsTemplateId()), RuoYiConfig.getSmsSign());
                //System.out.println(sms);
                // 设置缓存5分钟过期
                redisCache.setCacheObject(phone, verificationCode, 5, TimeUnit.MINUTES);
                if (phone.isEmpty()){
                    throw new IOException();
                } else if (phone.length()<11) {
                    throw new HTTPException(500,"");
                }
                return true;
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (HTTPException e) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }

    // 生成指定长度的验证码的方法
    private static String generateVerificationCode(int codeLength) {
        // 定义验证码字符集
        String codeChars = "0123456789";
        // 使用StringBuilder来拼接验证码
        StringBuilder verificationCode = new StringBuilder();
        // 创建Random对象
        Random random = new Random();
        // 循环生成指定长度的验证码
        for (int i = 0; i < codeLength; i++) {
            // 从字符集中随机选择一个字符
            char randomChar = codeChars.charAt(random.nextInt(codeChars.length()));
            // 将选定的字符追加到验证码中
            verificationCode.append(randomChar);
        }

        // 返回生成的验证码字符串
        return verificationCode.toString();
    }
}
